﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Linq.Expressions;
using System.Web.Mvc.Resources;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.ComponentModel;

namespace LizzabethBrownRealEstate.Models
{
    public partial class User
    {
        public string FullName { get { return this.First + " " + this.Last; } }

    }

    public partial class Location : INotifyPropertyChanging, INotifyPropertyChanged, IComparable<Location>
    {
        public int CompareTo(Location locationToCompare)
        {
            return this.Name.CompareTo(locationToCompare.Name);
        }
    }

    public partial class LBRDataContext
    {
        public RealEstateProperty GetRealEstateProperty(int id)
        {
            var rep = from rp in RealEstateProperties
                         where rp.PropertyId == id && rp.Deleted == false
                         select rp;
            RealEstateProperty property = rep.SingleOrDefault<RealEstateProperty>();
            return property;
        }

        public User GetUser(string id)
        {
            var u = from uzers in Users
                      where uzers.UserId.ToString() == id 
                      select uzers;
            User newUser = u.SingleOrDefault<User>();
            return newUser;
        }

        public Resource GetResource(int id)
        {
            var r = from res in Resources
                    where res.ResourceId == id && res.Deleted == false
                    select res;
            Resource newResource = r.SingleOrDefault<Resource>();
            return newResource;
        }

        public Category GetCategory(int id)
        {
            var c = from cat in Categories
                    where cat.CategoryId == id && cat.Deleted == false
                    select cat;
            Category newCategory = c.SingleOrDefault<Category>();
            return newCategory;
        }

        public Topic GetTopic(int id)
        {
            var t = from topic in Topics
                    where topic.TopicId == id && topic.Deleted == false
                    select topic;
            Topic newTopic = t.SingleOrDefault<Topic>();
            return newTopic;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Viewer")]
        public Message GetMessage(int id)
        {
            MembershipUser mu = Membership.GetUser();
            var m = from mess in Messages
                    where mess.MessageId == id && mess.Deleted == false
                    select mess;
            Message message;

            if (!Roles.IsUserInRole("Administrator"))
            {
                message = m.Where<Message>(_m => _m.UserId == (Guid)mu.ProviderUserKey).SingleOrDefault<Message>();
            }
            else
            {
                message = m.SingleOrDefault<Message>();
            }
            return message;
        }

        public Photo GetPhoto(int id)
        {
            var p = from pht in Photos
                    where pht.PhotoId == id && pht.Deleted == false
                    select pht;
            Photo newPhoto = p.SingleOrDefault<Photo>();
            return newPhoto;
        }

        public Event GetEvent(int id)
        {
            var e = from evt in Events
                    where evt.EventId == id && !evt.Deleted
                    select evt;
            Event newEvent = e.SingleOrDefault<Event>();
            return newEvent;
        }

        public Document GetDocument(int documentId)
        {
            var d = from doc in Documents
                    where doc.DocumentId == documentId && doc.Deleted == false
                    select doc;
            Document newDoc = d.SingleOrDefault();
            return newDoc;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Viewer")]
        public IEnumerable GetMessagesByTopic(int topicId)
        {
            IEnumerable messages;
            MembershipUser mu = Membership.GetUser();
            var m = from mess in Messages
                    where mess.TopicId == topicId && mess.Deleted == false
                    orderby mess.CreateDate descending
                    select mess;
            if (!Roles.IsUserInRole("Administrator"))
            {
                messages = m.Where<Message>(_m => _m.UserId == (Guid)mu.ProviderUserKey).AsEnumerable<Message>().OrderBy(_d=>_d.CreateDate.CompareTo(_d.CreateDate) < 0);
            }
            else
            {
                messages = m.AsEnumerable<Message>();
            }
            return messages;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Viewer")]
        public IEnumerable GetTopicsByCategory(int categoryId)
        {
            IEnumerable topics;
            MembershipUser mu = Membership.GetUser();
            var t = from tps in Topics
                    where tps.CategoryId == categoryId && tps.Deleted == false 
                    orderby tps.CreateDate descending
                    select tps;
            if (!Roles.IsUserInRole("Administrator"))
            {
                topics = t.Where<Topic>(_t=>_t.UserId == (Guid)mu.ProviderUserKey).AsEnumerable<Topic>();
            }
            else
            {
                topics = t.AsEnumerable<Topic>();
            }
            return topics;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Viewer")]
        public Location GetLocation(int locationId)
        {
            var l = from locs in Locations
                    where locs.LocationId == locationId && locs.Deleted == false
                    select locs;
            Location loc = l.SingleOrDefault<Location>();
            return loc;
        }

        public IEnumerable<RealEstateProperty> PropertySearch(RealEstateProperty r, List<Location> list)
        {
            bool hasparms = false;
            var props = from reps in RealEstateProperties
                        where (!reps.Deleted)
                        select reps;

            if (r.Basement.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Basement == r.Basement);
                hasparms = true;
            }
            if (r.Bathrooms.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Bathrooms == r.Bathrooms);
                hasparms = true;
            }
            if (r.Fireplaces.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Fireplaces == r.Fireplaces);
                hasparms = true;
            }
            if (r.FullBaths.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.FullBaths == r.FullBaths);
                hasparms = true;
            }
            if (r.NewConstruction.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.FullBaths == r.FullBaths);
                hasparms = true;
            }
            if (r.Price > 0)
            {
                props = props.Where<RealEstateProperty>(p => p.Price <= r.Price + 10000);
                hasparms = true;
            }
            if (r.Rooms.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Rooms == r.Rooms);
                hasparms = true;
            }
            if (r.TotalLivingArea.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.TotalLivingArea == r.TotalLivingArea);
                hasparms = true;
            }
            if (r.TotalSquareFeet.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.TotalSquareFeet == r.TotalSquareFeet);
                hasparms = true;
            }
            if (r.Garage.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Garage == r.Garage);
                hasparms = true;
            }
            if (r.GarageAttached.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.GarageAttached == r.GarageAttached);
                hasparms = true;
            }
            if (r.Frontage.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Frontage == r.Frontage);
                hasparms = true;
            }
            if (r.Historic.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Historic == r.Historic);
                hasparms = true;
            }
            if (!String.IsNullOrEmpty(r.MLSNumber))
            {
                props = props.Where<RealEstateProperty>(p => p.MLSNumber == r.MLSNumber);
                hasparms = true;
            }
            if (r.Bedrooms.HasValue)
            {
                props = props.Where<RealEstateProperty>(p => p.Bedrooms == r.Bedrooms);
                hasparms = true;
            }
            if (list.Count > 0)
            {
                props = props.Where<RealEstateProperty>(p => list.Contains<Location>(p.Location));
                hasparms = true;
            }

            IEnumerable<RealEstateProperty> ret = null;

            if (hasparms)
            {
                ret = props.AsEnumerable<RealEstateProperty>();
            }
            else
            {
                ret = props.Where<RealEstateProperty>(p=>p.PropertyId != p.PropertyId);
            }
            return ret;
        }

        public NewsItem GetNewsItem(int newsItemId)
        {
            var n = from item in NewsItems
                    where item.NewsItemId == newsItemId && item.Deleted == false
                    select item;

            return n.SingleOrDefault<NewsItem>();
        }
    }
}
